<template>
    <div class="edit-workorder app-container">
      <el-alert title="请输入工单内容，兼容Markdown语法，粘贴图片自动上传，提交给对应组成员处理."
                show-icon type="info" :closable="false" style="margin-bottom: 10px">
      </el-alert>

      <el-form :model="workOrder" ref="workOrderForm" :rules="rules">
        <div class="el-col-11">
        <el-form-item label="标题" label-width="65px" prop="title">
          <el-input type="text" v-model="workOrder.title" placeholder="工单标题，请尽可能简短有效"></el-input>
        </el-form-item>
        </div>

        <div class="el-col-11 el-col-offset-2">
          <el-form-item label="类型" label-width="65px" prop="type">
            <el-select v-model="workOrder.type" class="select" placeholder="请选择工单类型">
              <el-option v-for="(t, index) in typeList"
                         :label="t.desc" :value="t.id" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="el-col-11">
          <el-form-item label="接收组" label-width="65px" prop="group">
            <el-select v-model="group" class="select" placeholder="请选择接收组">
              <el-option v-for="(g, index) in groupList"
                         :label="g.name" :value="index" :key="g.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="el-col-11 el-col-offset-2">
          <el-form-item label="指派人" label-width="65px" prop="assign_to">
            <el-select v-model="workOrder.assign_to" class="select" placeholder="请选择工单处理人">
              <el-option v-for="(u, index) in assignToList"
                         :label="u.name?u.name:u.username" :value="u.id" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="el-col-24">
          <el-form-item label="内容" label-width="65px" prop="order_contents" class="md-form-item">
            <markdown-editor v-model="workOrder.order_contents"
                             :highlight="true"
                             preview-class="markdown-body"
                             ref="markdownEditor"></markdown-editor>
          </el-form-item>

          <el-form-item label="操作" label-width="65px">
            <el-button type="default" size="small" @click="resetForm">清空</el-button>
            <el-button type="primary" size="small" @click="handleSubmitWorkOrder">提交</el-button>
          </el-form-item>
        </div>

      </el-form>
    </div>
</template>

<script>
  import markdownEditor from 'vue-simplemde/src/markdown-editor'
  import 'simplemde/dist/simplemde.min.css'
  import 'github-markdown-css'
  import hljs from 'highlight.js'
  import 'highlight.js/styles/atom-one-light.css'

  import { uploadImageFile } from '@/api/workorder'

  window.hljs = hljs

  import { createWorkOrder } from '@/api/workorder'
  import { getGroupList } from '@/api/users'

  export default {
    name: 'edit-workorder',
    components: {
      markdownEditor
    },
    data() {
      return {
        group: '',
        groupList: [],
        assignToList: [],
        workOrder: {
          group: '',
          order_contents: '',
          assign_to: ''
        },
        html: '',
        rules: {
          title: [{ required: true, message: '请输入工单标题', trigger: 'blur' }],
          type: [{ required: true, message: '请选择工单类型', trigger: 'blur' }],
          group: [{ required: true, message: '请选择接收组', trigger: 'blur' }],
          order_contents: [{ required: true, message: '请输入工单内容', trigger: 'blur' }],
          assign_to: [{ required: true, message: '请选择工单处理人', trigger: 'blur' }]
        },
        typeList: [
          { id: 0, desc: '数据库（非SQL）' },
          { id: 1, desc: '线上服务' },
          { id: 2, desc: '计划任务' },
          { id: 3, desc: '配置文件' },
          { id: 4, desc: '操作系统' },
          { id: 5, desc: '其它' }
        ]
      }
    },
    watch: {
      'group'(val) {
        this.workOrder.assign_to = ''
        if (val || val === 0) {
          this.workOrder.group = this.groupList[val].id
          this.assignToList = this.groupList[val].users
        } else {
          this.assignToList = []
        }
      }
    },
    created() {
      this.fetchGroupList()
      this.editCopyImage()
    },
    methods: {
      fetchGroupList() {
        getGroupList({ page_size: 0 }).then(res => {
          this.groupList = res
        }).catch(() => {
          this.$message.error('获取用户组列表失败')
        })
      },
      resetForm() {
        this.group = ''
        this.workOrder = { order_contents: '', assign_to: '', group: '' }
        this.$refs['workOrderForm'].resetFields()
      },
      handleSubmitWorkOrder() {
        this.$refs['workOrderForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            createWorkOrder(this.workOrder).then(() => {
              this.$message.success('工单已提交，等待处理')
              this.resetForm()
              this.$router.push({ path: '/workorder/handle' })
            }).catch(() => {
              this.$message.error('工单提交失败')
            })
          })
      },
      editCopyImage() {
        this.$nextTick(() => {
          [this.$refs.markdownEditor].map(({ simplemde }) => { // 一共有三个编辑窗口，所以需要循环监听事件
            simplemde.codemirror.on('drop', (editor, e) => { // 拖拽图片的触发函数
              if (!(e.dataTransfer && e.dataTransfer.files)) {
                this.$message({
                  message: '该浏览器不支持操作',
                  type: 'error'
                })
                return
              }
              const dataList = e.dataTransfer.files
              const imageFiles = []
              for (let i = 0; i < dataList.length; i++) {
                if (dataList[i].type.indexOf('image') === -1) {
                  this.$message({
                    message: '仅支持图片拖拽',
                    type: 'error'
                  })
                  continue
                }
                imageFiles.push(dataList[i])
              }
              // this.uploadImagesFile(simplemde.codemirror, imageFiles)
              this.uploadImagesFile(simplemde.codemirror, dataList[0])
              e.preventDefault()
            })
            simplemde.codemirror.on('paste', (editor, e) => { // 粘贴图片的触发函数
              if (!(e.clipboardData && e.clipboardData.items)) {
                this.$message.error('该浏览器不支持操作')
                return
              }
              try {
                const dataList = e.clipboardData.items
                if (dataList[0].kind === 'file' && dataList[0].getAsFile().type.indexOf('image') !== -1) {
                  this.uploadImagesFile(simplemde.codemirror, dataList[0].getAsFile())
                  e.preventDefault() // 若粘贴图片则组织默认粘贴事件发生，若不是图片，触发默认事件
                }
              } catch (e) {
                this.$message.error('请确定你粘贴板是图片，而不是文件')
              }
            })
          })
        })
      },
      uploadImagesFile(simplemde, files) {
        const formData = new FormData()
        formData.append('file', files, files.name)
        uploadImageFile(files.name, formData).then(resps => {
          const { state, data } = resps
          if (!state) { // 如果不是图片文件，则跳过
            this.$message.error(data)
          }
          const url = `![](${location.origin + data})` // 拼接成markdown
          const content = simplemde.getValue()
          simplemde.setValue(content + url + '\n') // 和编辑框之前的内容进行拼接
        }).catch(() => {
          this.$message.error('上传图片失败')
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

  .edit-workorder {
    .select {
      width: 100%;
    }

    .md-form-item {
      margin-bottom: 0;
    }
  }
</style>
